<template>
  <div class="payment-callback">
    <h1>处理支付结果</h1>
    <el-card v-if="loading">
      <el-skeleton :rows="3" animated />
      <template #footer>
        <p>正在验证支付状态，请稍候...</p>
      </template>
    </el-card>
    <el-result
        v-else-if="error"
        icon="error"
        :title="error"
        sub-title="验证支付状态时出错"
    >
      <template #extra>
        <el-button type="primary" @click="retryVerification">重试</el-button>
      </template>
    </el-result>
    <el-result
        v-else
        :icon="paymentSuccess ? 'success' : 'warning'"
        :title="statusMessage"
    >
      <template #extra>
        <el-button v-if="paymentSuccess" type="primary" @click="goToOrderDetails">查看订单详情</el-button>
      </template>
    </el-result>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
const store = useStore();

const loading = ref(true);
const paymentSuccess = computed(() => store.getters['verifyPayment/getPaymentSuccess']);
const statusMessage = computed(() => store.getters['verifyPayment/getStatusMessage']);
const error = computed(() => store.getters['verifyPayment/getError']);

const verifyPayment = async () => {
  const token = route.query.token;
  const payerId = route.query.PayerID;

  if (!token || !payerId) {
    ElMessage.error('缺少必要的支付信息');
    loading.value = false;
    return;
  }

  try {
    await store.dispatch('verifyPayment/verifyPayment', { orderId: token });
  } catch (err) {
    console.error('Payment verification error:', err);
  } finally {
    loading.value = false;
  }
};

const retryVerification = () => {
  loading.value = true;
  verifyPayment();
};

const goToOrderDetails = () => {
  router.push('/order-list');
};

onMounted(() => {
  verifyPayment();
});
</script>

<style scoped>
.payment-callback {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
}
</style>
